package com.ccg.securityConfig;

import com.ccg.entity.Message;
import com.ccg.entity.User;
import com.ccg.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//登陆账户密码验证成功处理器,返回一个json对象,用于异步处理
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    UserService userService;
    private ObjectMapper objectMapper=new ObjectMapper();
    /**
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication   认证成功封装的用户信息
     * @throws IOException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException{
        User user = (User)authentication.getPrincipal();
        //将最后一次登陆时间设置为当前时间
        userService.updateLastLogin(user.getUsername());
        user.setPassword("");
        Message message = new Message(0,"登陆成功",user);
        String json = objectMapper.writeValueAsString(message);
        httpServletRequest.getSession().removeAttribute("checkCode");
        //System.out.println(json);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(json);
    }
}
